package org.cicd;

// traverse module tree into to list
def topologize(Map datas){


    // iteration queue
    def queue = []
    // modules in topologize order
    def t_queue = []

    queue.push(datas)

    while (!queue.isEmpty()){
        def t=queue.remove(0)
        t_queue.add(t)
        if(t.modules != null){
            for(m in t.modules){
                /*println "push module: ${t.name}: ${m.name}"*/
                def env = [:]
                if(t.env != null){
                    env.putAll(t.env)
                }
                if(m.env != null){
                    env.putAll(m.env)
                }
                m.env = env
                queue.add(m)
            }
        }
    }
    return t_queue;
}

// merge map,merge two map keys
def merge(Map a, Map b){
    def c = [:]
    if(a!=null && !a.isEmpty()){
        c.putAll(a)
    }
    if(b!=null && !b.isEmpty()){
        c.putAll(b)
    }
    return c;
}

// string substitute
// if word has placeholder,such as "hello ${hello}",envs is ["hello":"world"], return "hello world"
def substitute(String word,Map envs){
    // if envs has ["hello":"world"], then if word = "hello ${hello}",then p match "${hello}"
    def p = ~'\\$\\{\\w+}'
    def m = p.matcher(word)
    if (m){
        def iter = m.iterator();
        while (iter.hasNext()){
            def var = iter.next()
            // parse "${hello}" => "hello"
            def strip = var.toString().substring(2,var.toString().length()-1)
            if (envs.get(strip)!=null){
                // replace all ${hello} to key "hello" in envs
                word= word.replace(var,envs.get(strip))
            }
        }
    }
    return word
}

def step_log(String step){

    println "------------------------------["+ step + "]------------------------------"
}

// concat mainling list, such as turn [hello,world] into "hello,world"
def concatMailingList(List list){
    def str = ""
    for(e in list){
        str = str + "," + e
    }
    if(str.equals("")){
        return ""
    }else{
        return str.substring(1)
    }
}


// concat mainling list, such as turn [hello,world] into ["hello","world"]
def concatMailingList2(List list){
    def str = ""
    for(e in list){
        str = str + "," +"\""+e+"\""
    }
    if(str.equals("")){
        return ""
    }else{
        return "["+str.substring(1)+"]"
    }
}

def hello(){
    echo "hello"
}

return this